package net;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serveIP;
    private int servePort;

    //两个参数一会在发送数据的时候会用到
    //暂时把这两个参数存起来，以后备用
    public UdpEchoClient(String serveIP,int servePort) throws SocketException {
        //这里不是说没有端口，而是让操作系统自动指定一个闲置的空闲端口
        socket = new DatagramSocket();
        //假设severIP是形如 1.2.3.4 这种点分十进制的表示方式
        this.serveIP = serveIP;
        this.servePort = servePort;
    }

    public void Start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while(true){
            //1.从控制台读取用户输入的内容
            System.out.println("->: ");
            String request = scanner.next();

            //2.构造一个UDP请求，发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(this.serveIP),this.servePort);
            socket.send(requestPacket);

            //3.从服务器读取UDP请求响应数据，并解析
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());

            //4.把服务器响应的显示到控制台上
            System.out.println(response);

        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.Start();
    }
}
